package cn.com.dashihui.api.service;

import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.dashihui.api.common.ServiceOrderCode;
import cn.com.dashihui.api.dao.ServiceOrder;
import cn.com.dashihui.kit.CommonKit;

public class ServiceOrderService {
	/**
	 * 保存订单和订单清单
	 * @throws Exception
	 */
	public void saveOrderAndGoods(ServiceOrder order,String[] goodsidArray) throws Exception{
		String orderNum = order.getStr("orderNum");
		//保存订单
		order.save();
		//批量保存商品列表
		String sql = "INSERT INTO t_bus_service_order_list(orderNum,shopid,shopName,shopThumb,serviceid,serviceTitle,amount) SELECT ?,S.id shopid,S.name shopName,S.thumb shopThumb,SI.id serviceid,SI.title serviceTitle,SI.sellPrice FROM t_bus_service_shop_item SI INNER JOIN t_bus_service_shop S ON SI.shopid=S.id WHERE SI.id=?";
		Object[][] params = new Object[goodsidArray.length][2];
		for(int i=0;i<goodsidArray.length;i++){
			params[i][0] = orderNum;
			params[i][1] = goodsidArray[i];
		}
		Db.batch(sql, params, goodsidArray.length);
	}
	
	/**
	 * <red>注：2016/02/25，停止该方法在客户端的调用，家政类服务订单列表与其他类服务订单列表，统一调用UserController的serviceOrderList，本方法不删除只是为了适应旧版本客户端</red>
	 * 用户查询各种状态的订单列表
	 */
	public Page<Record> findByPage(int userid,int flag,int pageNum,int pageSize){
		if(flag==1){
			
			//1:待付款（“未支付”、“未过期”、“未删除”）
			String sql = "FROM t_bus_service_order WHERE userid=? AND payState=? AND orderState=? ORDER BY createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT * ",sql,userid,ServiceOrderCode.OrderPayState.NO_PAY,ServiceOrderCode.OrderState.NORMAL);
			
		}else if(flag==2){
			
			//2：待发货（“已支付”、“待发货”）
			String sql = "FROM t_bus_service_order WHERE userid=? AND payState=? AND deliverState=? AND orderState=? ORDER BY createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT * ",sql,userid,ServiceOrderCode.OrderPayState.HAD_PAY,ServiceOrderCode.OrderDispatchState.NO_DISPATCH,ServiceOrderCode.OrderState.NORMAL);
			
		}else if(flag==3){
			
			//3：待收货（“已发货”）
			String sql = "FROM t_bus_service_order WHERE userid=? AND deliverState=? AND orderState=? ORDER BY createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT * ",sql,userid,ServiceOrderCode.OrderDispatchState.HAD_DISPATCH,ServiceOrderCode.OrderState.NORMAL);
			
		}else if(flag==4){
			
			//4：已完成（“已支付”，“已发货”，“已完成”）
			String sql = "FROM t_bus_service_order WHERE userid=? AND payState=? AND deliverState=? AND orderState=? ORDER BY createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT * ",sql,userid,ServiceOrderCode.OrderPayState.HAD_PAY,ServiceOrderCode.OrderDispatchState.HAD_DISPATCH,ServiceOrderCode.OrderState.FINISH);
			
		}else{
			
			//不显示已删除、已过期的订单
			String sql = "FROM t_bus_service_order WHERE userid=? AND orderState!=? AND orderState!=? ORDER BY createDate DESC";
			return Db.paginate(pageNum, pageSize, "SELECT * ",sql,userid,ServiceOrderCode.OrderState.DELETE,ServiceOrderCode.OrderState.EXPIRE);
			
		}
	}
	
	/**
	 * 根据用户ID和订单号查询出订单<br/>
	 * 排除已删除、已过期的订单
	 */
	public ServiceOrder getOrderByOrderNum(int userid,String orderNum){
		return ServiceOrder.me().findFirst("SELECT * FROM t_bus_service_order WHERE userid=? AND orderNum=? AND orderState!=? AND orderState!=?",userid,orderNum,ServiceOrderCode.OrderState.DELETE,ServiceOrderCode.OrderState.EXPIRE);
	}
	
	/**
	 * 根据订单号查询出订单<br/>
	 * 排除已删除、已过期的订单
	 */
	public ServiceOrder getOrderByOrderNum(String orderNum){
		return ServiceOrder.me().findFirst("SELECT * FROM t_bus_service_order WHERE orderNum=? AND orderState!=? AND orderState!=?",orderNum,ServiceOrderCode.OrderState.DELETE,ServiceOrderCode.OrderState.EXPIRE);
	}
	
	/**
	 * 根据订单号查询服务列表
	 */
	public List<Record> getServiceListByOrderNum(String orderNum){
		return Db.find("SELECT shopid,shopName,shopThumb,serviceid,serviceTitle,amount FROM t_bus_service_order_list WHERE orderNum=?", orderNum);
	}
	
	/**
	 * 用户催单
	 */
	@Before(Tx.class)
	public ServiceOrder urgeOrder(int userid,String orderNum) throws Exception{
		if(Db.update("UPDATE t_bus_service_order SET urgeTimes=urgeTimes+1,urgeLastTime=now() WHERE userid=? AND orderNum=?",userid,orderNum)==1){
			return getOrderByOrderNum(orderNum);
		}
		throw new Exception("订单不存在");
	}
	
	/**
	 * 记录操作日志
	 */
	public void log(String orderNum, String user, String action, String content){
		Db.update("INSERT INTO t_bus_service_order_log(orderNum,user,action,content) VALUES(?,?,?,?)",orderNum,user,action,content);
	}
	
	/*************保存订单前，对订单数据进行验证的两个方法****************/
	
	/**
	 * 统计出服务项价格 保留两位小数(四舍五入)
	 */
	public double getAmount(String[] goodsidArray){ 
		String sql = "SELECT SUM(SI.sellPrice) amount FROM t_bus_service_shop_item SI INNER JOIN t_bus_service_shop S ON SI.shopid=S.id WHERE state!=2 AND SI.id IN("+CommonKit.join(",", goodsidArray)+")";
		return Db.queryDouble(sql);
	}
	
	/**
	 * 要提交订单中是否有  下架和删除的服务项
	 * 状态(state)，1：已上架，2：已下架
	 * @return true 有下架和删除的服务项
	 */
	public boolean hasDownOrDelGoods(String[] goodsidArray){
		String sql = "SELECT COUNT(*) FROM t_bus_service_shop_item SI INNER JOIN t_bus_service_shop S ON SI.shopid=S.id WHERE state!=2 AND SI.id IN("+CommonKit.join(",", goodsidArray)+")";
		if(Db.queryLong(sql)<goodsidArray.length){//下架和删除的产品
			return true;
		}else{
			return false;
		}
	}
}
